package ua.vn.ticket_scanner.nfc.ticket;

import android.content.Intent;
import android.nfc.tech.MifareClassic;
import ua.vn.ticket_scanner.nfc.NFCDevice;
import ua.vn.ticket_scanner.nfc.utils.Converter;

import java.io.IOException;


/**
 * Created by Ivan on 14.06.13.
 */
public class MifareClassicTicket extends NFCDevice {


    public MifareClassicTicket(Intent intent) {
        super(intent);
    }

    public byte[] readBlock(int blockIndex) {
        MifareClassic mifareClassic = MifareClassic.get(getTag());
        byte[] data = null;
        if(mifareClassic != null) {
            try {
                mifareClassic.connect();
                mifareClassic.authenticateSectorWithKeyA(blockIndex, MifareClassic.KEY_DEFAULT);
                data = mifareClassic.readBlock(mifareClassic.sectorToBlock(blockIndex));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    mifareClassic.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return data;
    }

    public boolean writeBlock(int blockIndex, String string) {
        byte[] data = Converter.toBytes(string);
        MifareClassic mifareClassic = MifareClassic.get(getTag());
        if(mifareClassic != null) {
            try {
                mifareClassic.connect();
                mifareClassic.authenticateSectorWithKeyA(blockIndex, MifareClassic.KEY_DEFAULT);
                mifareClassic.writeBlock(mifareClassic.sectorToBlock(blockIndex), data);
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    mifareClassic.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }
}
